﻿using DoNet.Common.Enums;
using DoNet.Common.Extensions;
using DoNet.Common.Helpers;
using DoNet.Core;
using DoNet.System.Dtos;
using DoNet.System.IRepositories;
using DoNet.System.IServices;
using DoNet.System.Models;

namespace DoNet.System.Services
{
    /// <summary>
    /// 
    /// </summary>
    public class TaskManagerService : BaseService<TaskManager, TaskManagerOutputDto>, ITaskManagerService
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly ITaskManagerRepository repository;
        private readonly ITaskJobsLogRepository taskJobsLogRepository;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_baseRepository"></param>
        /// <param name="_repository"></param>
        public TaskManagerService(IRepository<TaskManager> _baseRepository, ITaskManagerRepository _repository, ITaskJobsLogRepository _taskJobsLogRepository)
        {
            baseRepository = _baseRepository;
            repository = _repository;
            taskJobsLogRepository = _taskJobsLogRepository;
        }

        #region 同步方法
        /// <summary>
        /// 同步记录任务运行结果
        /// </summary>
        /// <param name="jobId">任务Id</param>
        /// <param name="jobAction">任务执行动作</param>
        /// <param name="blresultTag">任务执行结果表示，true成功，false失败，初始执行为true</param>
        /// <param name="resume">结果简述</param>
        /// <param name="desc">返回消息详情</param>
        public void RecordRun(long jobId, JobAction jobAction, bool blresultTag = true, string resume = "", string desc = "")
        {
            DateTime addTime = DateTime.Now;
            string taskName = "";
            bool status = false;
            string resumeLog = $"未能找到定时任务：{jobId}";

            TaskManager job = repository.GetById(jobId);
            if (job != null)
            {
                taskName = job.TaskName;
                if (!blresultTag)
                {
                    job.ErrorCount++;
                    job.LastErrorTime = addTime;
                    resumeLog = $"异常，" + resume;
                }
                else
                {
                    status = blresultTag;
                    resumeLog = $"正常，" + resume;
                }

                if (jobAction == JobAction.开始)
                {
                    job.RunCount++;
                    job.LastRunTime = addTime;
                    job.NextRunTime = CronHelper.GetCronExpression(job.Cron).GetNextValidTimeAfter(addTime)?.ObjectToDateTime();
                }
                repository.Update(job);
            }
            taskJobsLogRepository.Insert(new TaskJobsLog()
            {
                Id = IdGeneratorHelper.IdSnowflake(),
                CreatorTime = addTime,
                TaskId = jobId,
                TaskName = taskName,
                JobAction = jobAction.ObjectToString(),
                Status = status,
                Resume = resumeLog,
                Description = desc
            });
        }
        #endregion 同步方法

        #region 异步方法
        /// <summary>
        /// 异步记录任务运行结果
        /// </summary>
        /// <param name="jobId">任务Id</param>
        /// <param name="jobAction">任务执行动作</param>
        /// <param name="blresultTag">任务执行结果表示，true成功，false失败，初始执行为true</param>
        /// <param name="resume">结果简述</param>
        /// <param name="desc">返回消息详情</param>
        public async Task RecordRunAsync(long jobId, JobAction jobAction, bool blresultTag = true, string resume = "", string desc = "")
        {
            DateTime addTime = DateTime.Now;
            string taskName = "";
            bool status = false;
            string resumeLog = $"未能找到定时任务：{jobId}";

            TaskManager job = await repository.GetByIdAsync(jobId);
            if (job != null)
            {
                taskName = job.TaskName;
                if (!blresultTag)
                {
                    job.ErrorCount++;
                    job.LastErrorTime = addTime;
                    resumeLog = $"异常，" + resume;
                }
                else
                {
                    status = blresultTag;
                    resumeLog = $"正常，" + resume;
                }

                if (jobAction == JobAction.开始)
                {
                    job.RunCount++;
                    job.LastRunTime = addTime;
                    job.NextRunTime = CronHelper.GetCronExpression(job.Cron).GetNextValidTimeAfter(addTime)?.ObjectToDateTime();
                }
                await repository.UpdateAsync(job);
            }
            await taskJobsLogRepository.InsertAsync(new TaskJobsLog()
            {
                Id = IdGeneratorHelper.IdSnowflake(),
                CreatorTime = addTime,
                TaskId = jobId,
                TaskName = taskName,
                JobAction = jobAction.ObjectToString(),
                Status = status,
                Resume = resumeLog,
                Description = desc
            });
        }
        #endregion 异步方法
    }
}
